package fun.yegang.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;

@Slf4j
public class UserUtils {
    public static String getUserFromOauth2() {
        OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        if (token == null) {
            log.warn("Can not get keycloak user from request.");
            return null;
        }
        OAuth2User user = token.getPrincipal();
        if (user instanceof DefaultOidcUser oidcUser) {
            return oidcUser.getPreferredUsername();
        }
        if (user instanceof DefaultOAuth2User oAuth2User) {
            return oAuth2User.getName();
        }
        return user.getName();
    }

    public static Boolean isLogin(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated();
    }

}
